from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Pet(models.Model):
    name = models.CharField(max_length=100)
    breed = models.CharField(max_length=100, blank=True)
    coat = models.CharField(max_length=100, blank=True)
    coat_variety = models.CharField(max_length=100, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    sex = models.CharField(max_length=100, blank=True)
    size = models.CharField(max_length=100, blank=True)
    pet_image = models.ImageField(upload_to='images/', blank=True)
    allergy = models.CharField(max_length=100, blank=True)
    disease = models.CharField(max_length=100, blank=True)
    extra_info = models.CharField(max_length=1000, blank=True)
    chip_number = models.CharField(max_length=100, blank=True)
    chipping_date = models.DateField(null=True, blank=True)
    location_of_chip = models.CharField(max_length=100, blank=True)
    tattoo_number = models.CharField(max_length=100, blank=True)
    locator_data = models.CharField(max_length=100, blank=True)
    distinctive_marks = models.CharField(max_length=1000, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='pets')

    def __str__(self):
        return self.name + ' ' + self.owner.username


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sex = models.CharField(max_length=100, blank=True)
    address = models.CharField(max_length=100, blank=True)
    status = models.CharField(max_length=100, blank=True)
    contact = models.CharField(max_length=100, blank=True)
    avatar = models.ImageField(upload_to='avatars/', blank=True)
    user_category = models.CharField(max_length=100, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    reg_date = models.DateField(null=True, blank=True)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
